package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.DictMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-03-20
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {


    @Autowired
    IStudentFaceManyDetailService iStudentFaceManyDetailService;

    @Autowired
    IStudentMergeLogService iStudentMergeLogService;

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IStudentSignInService iStudentSignInService;

    @Autowired
    IStudentFaceDataService iStudentFaceDataService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ILeaveTeacherStudentService iLeaveTeacherStudentService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IOrganizationDepartmentPrincipalService iOrganizationDepartmentPrincipalService;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    ITypeValueDataService iTypeValueDataService;

    @Autowired
    IStudentSchoolService iStudentSchoolService;
    //@Autowired
    //IAliyunApiService iAliyunApiService;

    //合并试听并没有报名的学员
    @Override
    public void studentMerge(Student studentParam) throws Exception {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer faceType = 1;

        //报名的学生，即合并的学生
        Long studentId = studentParam.getId();
        Student student = this.getById(studentParam.getId());

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("student_id", studentId);
        studentFaceDataQueryWrapper.orderByDesc("id");
        studentFaceDataQueryWrapper.last("limit 1");
        StudentFaceData studentFaceData = iStudentFaceDataService.getOne(studentFaceDataQueryWrapper);
        if (studentFaceData != null) {
            List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.getStudentFaceManyDetailByStudentId(studentId, studentFaceData.getEntityId());
            for (StudentFaceManyDetail studentFaceManyDetail : studentFaceManyDetailList) {
                Student studentMore = this.getById(studentFaceManyDetail.getStudentId());
                if (studentMore != null) {
                    QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                    recordCourseQueryWrapper.eq("year_part", quarterNow.getYearPart());
                    recordCourseQueryWrapper.eq("quarter", quarterNow.getNum());
                    recordCourseQueryWrapper.eq("student_id", studentMore.getId());
                    recordCourseQueryWrapper.eq("course_type", 8);
                    recordCourseQueryWrapper.eq("lesson_type", 1);
                    recordCourseQueryWrapper.ne("check_type", 1);
                    recordCourseQueryWrapper.groupBy("subjects_id");
                    List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
                    boolean isDel = true;
                    for (RecordCourse recordCourse : recordCourseList) {
                        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                        orderDetailQueryWrapper.eq("student_id", studentMore.getId());
                        orderDetailQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                        orderDetailQueryWrapper.ne("status", 2);
                        Long count = iOrderDetailService.count(orderDetailQueryWrapper);
                        if (count > 0) {
                            //已经报名过，不合并
                            isDel = false;
                            continue;
                        }
                        UpdateWrapper<RecordCourse> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("student_id", studentMore.getId());
                        updateWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                        updateWrapper.eq("course_type", 8);//只合并试听的
                        //updateWrapper.eq("check_type", 1);
                        updateWrapper.set("student_id", student.getId());
                        iRecordCourseService.update(updateWrapper);

                        UpdateWrapper<StudentSignIn> signInUpdateWrapper = new UpdateWrapper<>();
                        signInUpdateWrapper.eq("student_id", studentMore.getId());
                        signInUpdateWrapper.eq("course_type", 8);
                        signInUpdateWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                        signInUpdateWrapper.set("student_id", student.getId());
                        iStudentSignInService.update(signInUpdateWrapper);

                        StudentMergeLog studentMergeLog = new StudentMergeLog();
                        studentMergeLog.setStudentId(studentMore.getId());
                        studentMergeLog.setToStudentId(student.getId());
                        studentMergeLog.setRemark("报名、分班、采集人脸合并,科目为" + CommonUtil.getSubjectsNameForId(Integer.parseInt(recordCourse.getSubjectsId().toString())));
                        iStudentMergeLogService.save(studentMergeLog);
                    }

                    if (recordCourseList.size() > 0 && isDel) {
                        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                        orderDetailQueryWrapper.eq("student_id", studentMore.getId());
                        orderDetailQueryWrapper.ne("status", 2);
                        Long count = iOrderDetailService.count(orderDetailQueryWrapper);
                        if (count.equals(0L)) {
                            iStudentFaceManyDetailService.delStudentFaceData(studentMore.getId(), faceType);
                            iStudentFaceManyDetailService.updateStudentFaceData(student.getId(), faceType);
                            this.removeById(studentMore.getId());
                        }
                        //orderDetailQueryWrapper.eq("year_part", quarterNow.getYearPart());
                        //orderDetailQueryWrapper.eq("quarter_num", quarterNow.getYearPart());
                    }
                }
            }
        }
    }

    /**
     * 学员调班，调整缴费率、续报率数据所属老师
     * -------------
     * 算做教学主管的：
     * ① 调出老师使用课次大于等于8次课，并且调出老师离职
     * ② 总使用课次大于等于8次课，并且前面的带班老师都没有上够8次课
     * -------------
     * 算做调出班级老师：
     * ③ 调出老师使用课次大于等于8次课，并且调出老师在职
     * -------------
     * 算做调入班级老师：
     * ④ 调出班级使用课次小于等于8次课，算调入班级教师的（不需要添加到leave_teacher_student表）
     * ⑤ 当前剩余课次大于等于15（缴费成功，处理之前缴费成功再调班的学生），并且原带班老师已离职，算作调入班级老师
     * ⑥ 调出班级后再缴费（缴费成功），原本算教学主管的数据变更为当前带班老师（单独从缴费调接口）
     */
    @Override
    public void leaveTeacherStudent(Grade grade) {
        Integer yearPart = grade.getYearPart();
        Integer quarterNum = grade.getQuarterNum();
        Long teacherId = grade.getTeacherId();
        Long subjectsId = grade.getSubjectsId();
        Long schoolId = grade.getSchoolId();
        Long inSchoolId = grade.getInSchoolId();

        // 判断员工状态是否为离职
        Staff outStaff = iStaffService.getById(teacherId);

        // 教学主管
        OrganizationDepartmentPrincipal organizationDepartmentPrincipal = iOrganizationDepartmentPrincipalService.getPrincipalByDepartmentId(yearPart, quarterNum, schoolId);

        for (String studentId : grade.getStudentIdList()) {
            // 是否添加过，如果添加过了不重复添加
            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("teacher_id", teacherId);
            queryWrapper.in("student_id", studentId);
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("subjects_id", subjectsId);
//            queryWrapper.eq("school_id", schoolId);
            queryWrapper.last("limit 1");
            Long count = iLeaveTeacherStudentService.count(queryWrapper);
            if (count > 0) {
                continue;
            }

            LeaveTeacherStudent leaveTeacherStudent = new LeaveTeacherStudent();
            leaveTeacherStudent.setYearPart(yearPart);
            leaveTeacherStudent.setQuarterNum(quarterNum);
            leaveTeacherStudent.setSchoolId(schoolId);
            leaveTeacherStudent.setInSchoolId(inSchoolId);
            leaveTeacherStudent.setTeacherId(teacherId);
            leaveTeacherStudent.setSubjectsId(subjectsId);
            leaveTeacherStudent.setStudentId(Long.valueOf(studentId));

            // 调出班级老师所带的使用课时
            Integer useCourseCount = studentGradeMapper.useCourseCountByTeacherId(yearPart, quarterNum, subjectsId, Long.valueOf(studentId), grade.getTeacherId());

            if (useCourseCount >= 24) {
                // 使用课次大于等于8
                if (outStaff.getStatus().getKey() == 2) {
                    // 老师离职
                    leaveTeacherStudent.setType(1);

                    // 剩余课时
                    Integer residueCourseCount = studentGradeMapper.getResidueCourseCount(yearPart, quarterNum, subjectsId, Long.valueOf(studentId));
                    if (residueCourseCount >= 45) {
                        // 当前剩余课次大于等于15，并且原带班老师已离职，算作调入班级老师
                        leaveTeacherStudent.setSchoolmasterId(grade.getInTeacherId());
                    } else {
                        // 调出老师使用课次大于等于8次课，并且调出老师离职，算作主管数据
                        if (organizationDepartmentPrincipal != null) {
                            leaveTeacherStudent.setSchoolmasterId(organizationDepartmentPrincipal.getStaffId());
                        }
                    }
                } else {
                    // 调出班级教师在职，算做调出班级教师
                    leaveTeacherStudent.setType(2);
                    leaveTeacherStudent.setSchoolmasterId(grade.getTeacherId());
                }

            } else {
                // 当前带班老师使用课次小于8
                // 学员总使用课时
                Integer allUseCourseCount = studentGradeMapper.useCourseCountByTeacherId(grade.getYearPart(), grade.getQuarterNum(), grade.getSubjectsId(), Long.valueOf(studentId), null);

                if (allUseCourseCount >= 24) {
                    // 上一个带班老师的使用课时 = 总使用课时 - 当前带班老师的使用课时
                    Integer beforeUseCourseCount = allUseCourseCount - useCourseCount;
                    if (beforeUseCourseCount < 24) {
                        // 总使用课次大于等于8次课，并且前面的带班老师都没有上够8次课，算做教学主管的数据
                        if (organizationDepartmentPrincipal != null) {
                            leaveTeacherStudent.setSchoolmasterId(organizationDepartmentPrincipal.getStaffId());
                        }
                    }
                }
            }

            iLeaveTeacherStudentService.save(leaveTeacherStudent);
        }
    }


    /**
     * 同步离职老师学员
     * -------------
     * 算做教学主管的：调出老师使用课次大于等于8次课，并且调出老师离职
     */
    @Override
    public void leaveTeacherStudentByStatus(Long teacherId) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Integer yearPart = 0;
        Integer quarterNum = 0;
        if (quarter != null) {
            yearPart = quarter.getYearPart();
            quarterNum = quarter.getNum();
        }

        // 获取使用课次大于等于8次课的学员
        List<StudentGrade> studentIdList = studentGradeMapper.useCourseCountByTeacherIdList(yearPart, quarterNum, 24, teacherId);

        for (StudentGrade studentGrade : studentIdList) {
            // 获取是否已经添加过
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("subjects_id", studentGrade.getSubjectsId());
            queryWrapper.in("student_id", studentGrade.getStudentId());
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.last("limit 1");
            LeaveTeacherStudent leaveTeacherStudent = iLeaveTeacherStudentService.getOne(queryWrapper);

            // 教学主管
            OrganizationDepartmentPrincipal organizationDepartmentPrincipal = iOrganizationDepartmentPrincipalService.getPrincipalByDepartmentId(yearPart, quarterNum, studentGrade.getSchoolId());

            if (leaveTeacherStudent == null) {
                leaveTeacherStudent = new LeaveTeacherStudent();
                leaveTeacherStudent.setYearPart(yearPart);
                leaveTeacherStudent.setQuarterNum(quarterNum);
                leaveTeacherStudent.setSchoolId(studentGrade.getSchoolId());
                leaveTeacherStudent.setInSchoolId(studentGrade.getSchoolId());
                leaveTeacherStudent.setTeacherId(teacherId);
                leaveTeacherStudent.setSubjectsId(studentGrade.getSubjectsId());
                leaveTeacherStudent.setStudentId(studentGrade.getStudentId());
                leaveTeacherStudent.setType(1);
                if (organizationDepartmentPrincipal != null) {
                    leaveTeacherStudent.setSchoolmasterId(organizationDepartmentPrincipal.getStaffId());
                }
                iLeaveTeacherStudentService.save(leaveTeacherStudent);
            } else {
                leaveTeacherStudent.setType(1);
                if (organizationDepartmentPrincipal != null) {
                    leaveTeacherStudent.setSchoolmasterId(organizationDepartmentPrincipal.getStaffId());
                }
                iLeaveTeacherStudentService.updateById(leaveTeacherStudent);
            }
        }

    }

    /**
     * 学员调班，调整缴费率、续报率数据所属老师
     * -------------
     * 调出班级后再缴费（缴费成功），原本算教学主管的数据变更为当前带班老师
     */
    @Override
    public void leaveTeacherStudentByPay(OrderDetail orderDetail) {
        Integer yearPart = orderDetail.getYearPart();
        Integer quarterNum = orderDetail.getQuarterNum();
        Long subjectsId = orderDetail.getSubjectsId();
        Long schoolId = orderDetail.getSchoolId();
        Long studentId = orderDetail.getStudentId();

        // 获取是否已经添加过
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("subjects_id", subjectsId);
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("year_part", yearPart);
        queryWrapper.eq("quarter_num", quarterNum);
        queryWrapper.eq("type", 1);// 离职数据
        queryWrapper.last("limit 1");
        LeaveTeacherStudent leaveTeacherStudent = iLeaveTeacherStudentService.getOne(queryWrapper);

        if (leaveTeacherStudent != null) {
            // 获取当前带班老师
            Grade grade = studentGradeMapper.gradeByStudentId(yearPart, quarterNum, subjectsId, studentId);
            if (grade != null) {
                // 原本带班老师已离职，算做现带班老师缴费成功
                leaveTeacherStudent.setType(1);
                leaveTeacherStudent.setSchoolmasterId(grade.getTeacherId());
                iLeaveTeacherStudentService.updateById(leaveTeacherStudent);
            }
        }
    }

    @Override
    public void  addOrUpdateData(Student student){
        if (student.getId() != null){
            student.setId(idWorker.nextId());
        }
        List<TypeValueData> typeValueDataList = new ArrayList<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        Integer i = 0;
        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            if (typeValueData.getTypeId() != null) {
                typeValueData.setForId(student.getId());
                typeValueData.setType(4);
                typeValueData.setContent(typeValueData.getContent().trim());
                typeValueDataList.add(typeValueData);
                if (i == 0) {
                    QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("num", typeValueData.getTypeId());
                    queryWrapper.eq("type", 4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if (dict != null) {
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent().trim());
                    }
                }
                i++;
            }
        }
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //生成音频
        if (student.getName() != null && !student.getName().isEmpty()) {
            //iAliyunApiService.ttsProcessGETRequet(student);
        }
        this.saveOrUpdate(student);
        iStudentSchoolService.addOrUpdateData(student.getId(), student.getSchoolId());
    }
}
